//
//  UIImage+additions.swift
//  HaoLie
//
//  Created by arkin on 17/04/2017.
//  Copyright © 2017 higgs. All rights reserved.
//

import UIKit

extension UIImage {
    class public func image(from color:UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(CGSize(width:1, height:1), false, 0)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(CGRect(x:0, y:0, width:1, height:1))
        let desImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return desImage!
    }
    
    public func resize(to size:CGSize) -> UIImage {
        let targetSize = UIImage.targetSize(from: self.size, to: size)
        UIGraphicsBeginImageContextWithOptions(targetSize, false, 0)
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: targetSize))
        let desImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return desImage!
    }
    
    public func data(_ rate: CGFloat = 0.2) -> Data? {
        return UIImage.jpegData(self)(compressionQuality:rate)
    }
    
    public class func targetSize(from: CGSize, to: CGSize) -> CGSize {
        if from.width == 0 || from.height == 0{
            return CGSize(width: 200, height: 140)
        }
        var targetSize = to
        if from.width / from.height <= targetSize.width / targetSize.height {
            targetSize.width = ceil(from.width * targetSize.height / from.height)
        } else {
            targetSize.height = ceil(from.height * targetSize.width / from.width)
        }
        return targetSize
    }
}

